import fs from 'fs'
import path from 'path'
import _ from 'lodash'
import remoteTools from './remoteTools'
import canvasBuffer from './electron-canvas-to-buffer'

function sleep(time = 0) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, time);
  })
};

// 删除文件夹
function delDir(path) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach((file, index) => {
      let curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) {
        delDir(curPath); //递归删除文件夹
      } else {
        fs.unlinkSync(curPath); //删除文件
      }
    });
    fs.rmdirSync(path);
  }
}

// 保存 canvas 内容到图片
function saveCanvasToImage(canvas) {
  return new Promise((resolve, reject) => {
    // as a buffer
    const buffer = canvasBuffer(canvas, 'image/png');
    let outputPath = path.resolve(remoteTools.getTmpDir(), 'inmobi', 'coverimg_' + Math.floor(Math.random()*10000+0) + '.png');

    // write canvas to file
    fs.writeFile(outputPath, buffer, function (err) {
      if (err) {
        reject(err.message);
      } else {
        resolve(outputPath);
      }
    })
  })
}

export default {
  sleep,
  delDir,
  saveCanvasToImage,
}
